<template>
  <div class="file-transfer-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文件传输</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="密钥传输" name="key">
          <div class="key-transfer">
            <el-card class="transfer-card">
              <template #header>
                <div class="card-header">
                  <span>发送文件</span>
                </div>
              </template>
              <el-upload
                class="upload-area"
                drag
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :limit="1"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  拖拽文件到此处，或 <em>点击上传</em>
                </div>
              </el-upload>
              <div class="key-display" v-if="transferKey">
                <p>传输密钥：<span class="key">{{ transferKey }}</span></p>
                <p class="key-tip">请将此密钥提供给接收方</p>
                <el-button type="primary" @click="startSendFile">开始传输</el-button>
              </div>
              <div v-else>
                <el-button type="primary" @click="generateKey" :disabled="!selectedFile">生成传输密钥</el-button>
              </div>
            </el-card>
            
            <el-card class="transfer-card">
              <template #header>
                <div class="card-header">
                  <span>接收文件</span>
                </div>
              </template>
              <el-form :model="receiveForm" label-width="100px">
                <el-form-item label="传输密钥">
                  <el-input v-model="receiveForm.key" placeholder="请输入传输密钥" @blur="checkTransferKey"></el-input>
                </el-form-item>
                <div v-if="fileKeyError" style="color: red; margin-bottom: 10px;">{{ fileKeyError }}</div>
                <div v-if="fileInfo" class="file-info" style="margin-bottom: 10px;">
                  <p>文件名：{{ fileInfo.fileName }}</p>
                  <p>文件大小：{{ formatFileSize(fileInfo.fileSize) }}</p>
                </div>
                <el-form-item>
                  <el-button type="primary" @click="receiveFile" :disabled="!fileReadyToReceive">接收文件</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="直接传输" name="direct">
          <div class="direct-transfer">
            <el-table :data="deviceList" stripe style="width: 100%">
              <el-table-column prop="deviceName" label="设备名称"></el-table-column>
              <el-table-column prop="ipAddress" label="IP地址"></el-table-column>
              <el-table-column prop="status" label="在线状态">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                    {{ scope.row.status === 1 ? '在线' : '离线' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button size="small" type="primary" @click="sendToDevice(scope.row)" :disabled="scope.row.status !== 1">
                    发送文件
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-if="deviceList.length === 0" description="暂无可用设备"></el-empty>
          </div>
        </el-tab-pane>

        <el-tab-pane label="传输记录" name="history">
          <el-table :data="transferHistory" stripe style="width: 100%">
            <el-table-column prop="fileName" label="文件名"></el-table-column>
            <el-table-column prop="fileSize" label="文件大小">
              <template #default="scope">
                {{ formatFileSize(scope.row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column prop="transferType" label="传输类型">
              <template #default="scope">
                {{ scope.row.transferType === 'send' ? '发送' : '接收' }}
              </template>
            </el-table-column>
            <el-table-column label="对方">
              <template #default="scope">
                {{ scope.row.transferType === 'send' ? scope.row.receiverName : scope.row.senderName }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="传输时间"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="transferHistory.length === 0" description="暂无传输记录"></el-empty>
        </el-tab-pane>
      </el-tabs>

      <!-- 文件选择对话框 -->
      <el-dialog v-model="fileSelectDialog.visible" :title="fileSelectDialog.title" width="30%">
        <el-upload
          class="upload-area"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleDirectFileChange"
          :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处，或 <em>点击上传</em>
          </div>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="fileSelectDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="startDirectTransfer" :disabled="!directFile">发送</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 传输进度对话框 -->
      <el-dialog v-model="transferDialog.visible" :title="transferDialog.title" width="30%" :close-on-click-modal="false">
        <div class="transfer-progress">
          <el-progress :percentage="transferProgress" :status="transferStatus"></el-progress>
          <p class="transfer-info">{{ transferInfo }}</p>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="transferDialog.visible = false" :disabled="transferProgress < 100 && transferProgress > 0">关闭</el-button>
            <el-button type="danger" @click="cancelTransfer" :disabled="transferProgress >= 100">取消传输</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { getOnlineDevices } from '@/api/device';
import { useDeviceStore } from '@/store/deviceStore';
import { 
  createFileTransfer, 
  uploadFile, 
  getFileTransferByKey, 
  getSentFiles, 
  getReceivedFiles,
  updateFileTransferStatus,
  downloadFile
} from '@/api/fileTransfer';

const deviceStore = useDeviceStore();
const activeTab = ref('key');
const deviceList = ref([]);
const transferHistory = ref([]);
const selectedFile = ref(null);
const directFile = ref(null);
const transferKey = ref('');
const transferProgress = ref(0);
const transferStatus = ref('');
const transferInfo = ref('');
const fileInfo = ref(null);
const fileKeyError = ref('');
const fileReadyToReceive = ref(false);

const receiveForm = reactive({
  key: ''
});

const transferDialog = reactive({
  visible: false,
  title: '文件传输'
});

const fileSelectDialog = reactive({
  visible: false,
  title: '选择要发送的文件',
  targetDevice: null
});

// 加载设备列表
const loadDeviceList = async () => {
  try {
    const res = await getOnlineDevices();
    deviceList.value = res.data.filter(device => device.id !== deviceStore.currentDevice.id);
  } catch (error) {
    console.error('加载设备列表失败:', error);
    ElMessage.error('加载设备列表失败');
  }
};

// 加载传输历史记录
const loadTransferHistory = async () => {
  try {
    const deviceId = deviceStore.currentDevice.id;
    const [sentRes, receivedRes] = await Promise.all([
      getSentFiles(deviceId),
      getReceivedFiles(deviceId)
    ]);
    
    // 合并发送和接收的记录
    const sentFiles = sentRes.data || [];
    const receivedFiles = receivedRes.data || [];
    
    // 处理数据格式，添加transferType字段
    sentFiles.forEach(file => {
      file.transferType = 'send';
    });
    
    receivedFiles.forEach(file => {
      file.transferType = 'receive';
    });
    
    // 合并并按时间排序
    transferHistory.value = [...sentFiles, ...receivedFiles].sort((a, b) => {
      return new Date(b.createTime) - new Date(a.createTime);
    });
  } catch (error) {
    console.error('加载传输历史失败:', error);
    ElMessage.error('加载传输历史失败');
    transferHistory.value = [];
  }
};

// 文件改变事件（密钥传输）
const handleFileChange = (file) => {
  selectedFile.value = file;
  transferKey.value = ''; // 清除之前的密钥
};

// 文件改变事件（直接传输）
const handleDirectFileChange = (file) => {
  directFile.value = file;
};

// 生成传输密钥
const generateKey = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件');
    return;
  }

  try {
    // 上传文件并创建传输记录
    const uploadRes = await uploadFile(selectedFile.value.raw);
    if (!uploadRes.data) {
      ElMessage.error('文件上传失败');
      return;
    }

    // 生成6位数字密钥
    const key = Math.floor(100000 + Math.random() * 900000).toString();
    
    // 创建文件传输记录
    const fileTransferData = {
      fileName: selectedFile.value.name,
      fileSize: selectedFile.value.size,
      filePath: uploadRes.data,
      transferKey: key,
      senderId: deviceStore.currentDevice.id,
      senderName: deviceStore.currentDevice.deviceName,
      status: 0 // 等待中
    };
    
    const createRes = await createFileTransfer(fileTransferData);
    if (createRes.code === 200) {
      transferKey.value = key;
      ElMessage.success('密钥生成成功');
    } else {
      ElMessage.error('创建传输记录失败');
    }
  } catch (error) {
    console.error('生成密钥失败:', error);
    ElMessage.error('生成密钥失败');
  }
};

// 开始发送文件（密钥传输）
const startSendFile = async () => {
  if (!selectedFile.value || !transferKey.value) {
    ElMessage.warning('请选择文件并生成密钥');
    return;
  }
  
  transferDialog.visible = true;
  transferDialog.title = '发送文件';
  transferProgress.value = 0;
  transferStatus.value = '';
  transferInfo.value = `正在发送文件: ${selectedFile.value.name}`;
  
  // 模拟文件传输进度（实际上此时文件已经上传到服务器，等待接收方下载）
  simulateTransferProgress();
};

// 校验密钥并展示文件信息
const checkTransferKey = async () => {
  fileKeyError.value = '';
  fileInfo.value = null;
  fileReadyToReceive.value = false;
  if (!receiveForm.key) {
    fileKeyError.value = '请输入传输密钥';
    return;
  }
  try {
    const res = await getFileTransferByKey(receiveForm.key);
    if (res.data) {
      fileInfo.value = res.data;
      fileReadyToReceive.value = true;
    } else {
      fileKeyError.value = '密钥不存在或文件已失效';
    }
  } catch (e) {
    fileKeyError.value = '密钥不存在或文件已失效';
  }
};

// 接收文件
const receiveFile = async () => {
  if (!fileReadyToReceive.value) {
    ElMessage.warning('请先输入有效的传输密钥');
    return;
  }
  
  transferDialog.visible = true;
  transferDialog.title = '接收文件';
  transferProgress.value = 0;
  transferStatus.value = '';
  transferInfo.value = `正在接收文件: ${fileInfo.value.fileName}`;
  
  try {
    // 准备接收者信息
    const receiverInfo = {
      receiverId: deviceStore.currentDevice.id,
      receiverName: deviceStore.currentDevice.deviceName
    };
    
    // 更新文件状态为传输中(1)并设置接收者信息
    const updateRes = await updateFileTransferStatus(fileInfo.value.id, 1, receiverInfo);
    if (!updateRes.data) {
      ElMessage.error('更新文件状态失败');
      transferStatus.value = 'exception';
      transferInfo.value += ' (失败)';
      return;
    }
    
    // 模拟文件下载进度
    simulateTransferProgress(() => {
      // 下载完成后触发实际的文件下载
      ElMessage.info('准备下载文件，请稍候...');
      
      // 使用window.open直接下载，使用不经过前端路由的路径
      const host = window.location.protocol + '//' + window.location.host;
      const timestamp = new Date().getTime(); // 添加时间戳避免缓存
      // 直接使用/file/download路径，这个路径已经在vite.config.js中配置为代理
      const downloadUrl = `${host}/file/download/${fileInfo.value.id}?t=${timestamp}`;
      
      console.log('文件下载地址:', downloadUrl);
      
      // 直接在新窗口打开下载链接
      window.open(downloadUrl, '_blank');
      
      // 下载完成后，更新文件状态为已完成(2)
      setTimeout(async () => {
        try {
          const updateRes = await updateFileTransferStatus(fileInfo.value.id, 2);
          if (updateRes.data) {
            ElMessage.success('文件下载完成');
            // 立即刷新传输历史
            await loadTransferHistory();
          } else {
            console.error('更新文件状态失败');
          }
        } catch (err) {
          console.error('更新文件状态失败:', err);
        }
      }, 10000); // 增加到10秒
    });
  } catch (error) {
    console.error('接收文件失败:', error);
    ElMessage.error('接收文件失败');
    transferStatus.value = 'exception';
    transferInfo.value += ' (失败)';
  }
};

// 发送文件到设备（直接传输）
const sendToDevice = (device) => {
  fileSelectDialog.targetDevice = device;
  fileSelectDialog.visible = true;
};

// 开始直接传输
const startDirectTransfer = () => {
  if (!directFile.value || !fileSelectDialog.targetDevice) {
    ElMessage.warning('请选择文件');
    return;
  }
  
  fileSelectDialog.visible = false;
  transferDialog.visible = true;
  transferDialog.title = '发送文件';
  transferProgress.value = 0;
  transferStatus.value = '';
  transferInfo.value = `向 ${fileSelectDialog.targetDevice.deviceName} 发送文件: ${directFile.value.name}`;
  
  // 模拟文件传输进度
  simulateTransferProgress();
};

// 模拟传输进度
const simulateTransferProgress = (callback) => {
  let progress = 0;
  const interval = setInterval(() => {
    progress += Math.floor(Math.random() * 10) + 1;
    if (progress >= 100) {
      progress = 100;
      transferStatus.value = 'success';
      transferInfo.value += ' (完成)';
      clearInterval(interval);
      
      if (typeof callback === 'function') {
        callback();
      }
    }
    transferProgress.value = progress;
  }, 300);
};

// 取消传输
const cancelTransfer = () => {
  transferStatus.value = 'exception';
  transferInfo.value += ' (已取消)';
  ElMessage.info('传输已取消');
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
  }
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'; // 等待接收
    case 1: return 'warning'; // 传输中
    case 2: return 'success'; // 已完成
    case 3: return 'danger'; // 已取消
    case 4: return 'danger'; // 传输失败
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '等待接收';
    case 1: return '传输中';
    case 2: return '已完成';
    case 3: return '已取消';
    case 4: return '传输失败';
    default: return '未知';
  }
};

onMounted(() => {
  loadDeviceList();
  loadTransferHistory();
  
  // 定时刷新设备列表和传输历史
  const deviceInterval = setInterval(loadDeviceList, 30000);
  const historyInterval = setInterval(loadTransferHistory, 60000);
  
  onUnmounted(() => {
    clearInterval(deviceInterval);
    clearInterval(historyInterval);
  });
});
</script>

<style scoped>
.file-transfer-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.key-transfer {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.transfer-card {
  flex: 1;
}

.key-display {
  margin-top: 20px;
  text-align: center;
}

.key {
  font-size: 24px;
  color: #409EFF;
  font-weight: bold;
}

.key-tip {
  color: #666;
  margin: 10px 0;
}

.transfer-progress {
  padding: 20px 0;
}

.transfer-info {
  margin-top: 10px;
  color: #666;
}

.upload-area {
  width: 100%;
}

.direct-transfer {
  margin-top: 20px;
}
</style> 